<script setup>
import {ref} from "vue";
import SubmitAnswer from "../../student/practice/SubmitAnswer.vue";
import DoAnswer from "./DoAnswer.vue";
import router from "../../../router/index.js";
import {
  getAssignment,
  getAssignmentQuestionOptions, getStudentAssignmentAnswer, isSubmitAssignment,
  listAssignmentQuestions, submitAssignment, submitAssignmentAnswer, submitExam
} from "../../../api/course/course.js";
import {ArrowLeftBold, ArrowRightBold} from "@element-plus/icons-vue";
import {ElMessage, ElNotification} from "element-plus";
import {assignIn} from "lodash";
// 题型数组
const type = ref(['单选题', '多选题', '判断题', '填空题', '问答题'])
// 题目数组
const practices = ref([])
// 是否已经提交
const isSubmit = ref()
// 总题目数
const total = ref(10)
// 单个题目
const question = ref({})
// 作业题目数组(解析个屁,顺序查询)
const assignmentQuestions = ref([])
// 作业信息
const assignment = ref({});
// 当前题目索引
const questionIndex = ref(0);
// 正确答案数组
const rightAnswer = ref([]);
// 单选选项
const radioOptions = ref([{
  value: 'A',
  content: '',
  checked: 0 // 选项未选中状态
}, {
  value: 'B',
  content: '',
  checked: 0 // 选项未选中状态
}, {
  value: 'C',
  content: '',
  checked: 0 // 选项未选中状态
}, {
  value: 'D',
  content: '',
  checked: 0
}]);
//多选选项
const checkboxOptions = ref([{
  value: 'A',
  content: '',
  checked: 0 // 选项未选中状态
}, {
  value: 'B',
  content: '',
  checked: 0 // 选项未选中状态
}, {
  value: 'C',
  content: '',
  checked: 0 // 选项未选中状态
}, {
  value: 'D',
  content: '',
  checked: 0
}])
// 判断题选项
const judgeOptions = ref([{
  value: 'T',
  content: '',
  checked: 0 // 选项未选中状态
}, {
  value: 'F',
  content: '',
  checked: 0 // 选项未选中状态
}])
// 获取题目选项
const handleGetQuestionOptions = async () => {
  await getAssignmentQuestionOptions(question.value.id).then(res => {
    option.value = res.data;
    // 给选项赋值
    assignOption();
  })
}
// 选项对象
const option = ref({
  practiceId: 0,
  a: '',
  b: '',
  c: '',
  d: ''
})
// 判断是否是选择
const isOption = () => {
  if (question.value.type === 0) {
    // console.log("单选");
    option.value.a = radioOptions.value[0].content;
    option.value.b = radioOptions.value[1].content;
    option.value.c = radioOptions.value[2].content;
    option.value.d = radioOptions.value[3].content;
    return true;
  } else if (question.value.type === 1) {
    // console.log("多选");
    option.value.a = checkboxOptions.value[0].content;
    option.value.b = checkboxOptions.value[1].content;
    option.value.c = checkboxOptions.value[2].content;
    option.value.d = checkboxOptions.value[3].content;
    return true;
  } else if (question.value.type === 2) {
    // console.log("判断");
    option.value.a = judgeOptions.value[0].content;
    option.value.b = judgeOptions.value[1].content;
    return true;
  } else return false;
}

// 选项赋值
const assignOption = () => {
  if (question.value.type === 0) {
    radioOptions.value[0].content = option.value.a;
    radioOptions.value[1].content = option.value.b;
    radioOptions.value[2].content = option.value.c;
    radioOptions.value[3].content = option.value.d;
  } else if (question.value.type === 1) {
    checkboxOptions.value[0].content = option.value.a;
    checkboxOptions.value[1].content = option.value.b;
    checkboxOptions.value[2].content = option.value.c;
    checkboxOptions.value[3].content = option.value.d;
  } else if (question.value.type === 2) {
    judgeOptions.value[0].content = option.value.a;
    judgeOptions.value[1].content = option.value.b;
  }
}
// 获取作业id
const assignmentId = ref();
assignmentId.value = router.currentRoute.value.params.id;


// 获取作业信息
const handleGetAssignment = async () => {
  console.log(assignmentId.value)
  await getAssignment(assignmentId.value).then(res => {
    assignment.value = res.data;
    //   获取作业题目
    handleListAssignmentQuestions()

  })
}

// 获取当前作业所有题目
const handleListAssignmentQuestions = async () => {
  await listAssignmentQuestions(assignmentId.value).then(res => {
    assignmentQuestions.value = res.data;
    handleIsSubmitAssignment().then(res => {
      if (!isSubmit.value){
        console.log("未提交");
        assignmentQuestions.value.map(question => question.answer = []);
      }
      else {
        console.log("已提交");
        //   获取作业答案
        rightAnswer.value = assignmentQuestions.value.map(question => question.answer);
        console.log(rightAnswer.value);
        assignmentQuestions.value.map(question => question.answer=[]);
        handleGetStudentAssignmentAnswer();
      }
    });
    console.log(assignmentQuestions.value);
    //   获取第一个题目
    question.value = assignmentQuestions.value[0];
    if (isOption())
      handleGetQuestionOptions();
    //   解析题目数组为跳转卡片
    handleAssignmentQuestionsToPractices();
  })
}

// 查询学生是否已经提交过作业
const handleIsSubmitAssignment = async () => {
  await isSubmitAssignment(assignmentId.value).then(res => {
    isSubmit.value = res.data;
    console.log(isSubmit.value);
  })
}

// 获取学生作业答案
const handleGetStudentAssignmentAnswer = async () => {
  await getStudentAssignmentAnswer(isSubmit.value.id).then(res => {
    console.log(res.data);
    assignmentQuestions.value = assignmentQuestions.value.map((question, index) => {
      const matchingItem = res.data.find(item => item.assignmentQuestionId === question.id);
      if (matchingItem) {
        question.answer = matchingItem.answer;
      }
      return question;
    });
    console.log(assignmentQuestions.value);
  })
}

// 解析题目数组
const handleAssignmentQuestionsToPractices = () => {
  for (let i = 0; i < assignmentQuestions.value.length; i++) {
    if (!practices.value.map(practice => practice.type).includes(assignmentQuestions.value[i].type)) {
      practices.value.push({
        type: assignmentQuestions.value[i].type,
        content: [assignmentQuestions.value[i]]
      })
      // console.log(practices.value);
    } else {
      // console.log(practices.value.map(practice=>practice.type).indexOf(item));
      // 获取题目内容
      practices.value[practices.value.map(practice => practice.type).indexOf(assignmentQuestions.value[i].type)].content.push(assignmentQuestions.value[i]);
    }
  }// console.log(practices.value)
}
// 跳转题目
const handleGetQuestion = (item) => {
  question.value = item;
  questionIndex.value = assignmentQuestions.value.indexOf(item);
  console.log(questionIndex.value);
  if (isOption())
    handleGetQuestionOptions();
}
// 跳转上一题
const handleLeftQuestion = () => {
  question.value = assignmentQuestions.value[questionIndex.value - 1];
  questionIndex.value--;
  if (isOption())
    handleGetQuestionOptions();
}
// 跳转下一题
const handleRightQuestion = () => {
  question.value = assignmentQuestions.value[questionIndex.value + 1];
  questionIndex.value++;
  if (isOption())
    handleGetQuestionOptions();
}


// 提交作业
const handleSubmitAssignment = async () => {
  await submitAssignment(assignmentId.value).then(res => {
    const studentQuestionId = res.data;
    const studentAnswer = practices.value.flatMap(practice => practice.content.map(
        question => {
          if (Array.isArray(question.answer) && question.answer.length === 0) {
            return null; // 或者直接返回 undefined
          }
          return {
            answer: typeof question.answer === 'object' && question.answer instanceof Array ? '' : question.answer,
            studentAssignmentId: studentQuestionId,
            assignmentQuestionId: question.id
          };
        }
    ).filter(Boolean)); // 使用 filter(Boolean) 来过滤掉 null 或 undefined 的元素
    console.log(studentAnswer);
    submitAssignmentAnswer(studentAnswer).then(res => {
      ElMessage.success("提交成功");
      router.push("/course/assignment")
    })
  })
}

handleGetAssignment()


</script>

<template>
  <div class="common-layout">
    <el-container>
      <el-header style="background: #3a4357;height: 10vh">
        <div style="display: flex; align-items: center; height: 100%;">
          <span style="color: white;margin-left: 50%">{{ assignment.name }}</span>
          <el-button type="primary" style="margin-left: 500px" @click="handleSubmitAssignment" v-if="!isSubmit">提交作业</el-button>
        </div>
      </el-header>
      <el-container>
        <el-main style="height: 90vh;">
          <div style="display: flex;justify-content: space-between;">
            <el-icon size="30" style="margin-top: 42vh" @click="handleLeftQuestion()" v-if="questionIndex!==0">
              <ArrowLeftBold/>
            </el-icon>
            <el-icon size="30" v-if="questionIndex===0"></el-icon>
            <!--          题型-->
            <div>
              <h3>{{ type[question.type] }}</h3>
              <!--          题目-->
              <div style="height: 60vh;display: flex">
                <el-form
                    :label-position="'top'"
                    label-width="auto"
                    :model="question"
                    style="max-width: 900px"
                >
                  <el-form-item label="题目内容">
                    <div>{{ question.content }}</div>
                  </el-form-item>
                  <!--        题目类型选择-->
                  <DoAnswer :practice="question" :radioOptions="radioOptions" :judge-options="judgeOptions"
                            :checkbox-options="checkboxOptions"></DoAnswer>
                </el-form>
              </div>
              <div v-if="isSubmit">正确答案:{{rightAnswer[questionIndex]}}</div>
            </div>
            <el-icon size="30" style="margin-top: 42vh" v-if="questionIndex!==assignmentQuestions.length-1"
                     @click="handleRightQuestion()">
              <ArrowRightBold/>
            </el-icon>
            <el-icon size="30" v-if="questionIndex===assignmentQuestions.length-1"></el-icon>
          </div>
          <div style="display: flex;justify-content: center;margin-top: 10vh">
            <!--            <el-button type="success" @click="submitQuestionAnswer(questionIndex)">提交当前题目答案</el-button>-->
          </div>
        </el-main>
        <el-divider direction="vertical" style="height: 90vh"/>
        <el-aside width="300px" style="height: 90vh;">
          <!--          侧边跳转-->
          <!--          for循环进行题目跳转-->
          <el-card style="width: 280px;margin-top: 40px" v-for="(practice,index) in practices" :key="index">
            <!--            题型-->
            <h3>{{ type[practice.type] }}</h3>
            <el-row :gutter="12">
              <el-col :span="6" v-for="(item,index) in practice.content" :key="item">
                <el-card style="width: 100%;margin-bottom: 10px" shadow="hover" @click="handleGetQuestion(item)">
                  {{ index + 1 }}
                </el-card>
              </el-col>
            </el-row>

          </el-card>
        </el-aside>
      </el-container>
    </el-container>
  </div>
</template>

<style scoped lang="less">


</style>